import 'dart:async';

import 'package:flutter/material.dart';
import 'package:like_chat/blocs/history_chat_bloc.dart';
import 'package:like_chat/dto/history_chat.dart';
import 'package:like_chat/entity/user.dart';
import 'package:like_chat/pages/chat_page.dart';
import 'package:web_socket_channel/io.dart';

class HistoryChatPage extends StatefulWidget {
  final User user;
  final HistoryChatBloc bloc;
  final IOWebSocketChannel webSocketChannel;
  final ValueChanged<bool> valueChanged;

  HistoryChatPage({@required this.valueChanged, @required this.user, @required this.bloc, @required this.webSocketChannel});

  @override
  _HistoryChatPageState createState() => _HistoryChatPageState();
}

class _HistoryChatPageState extends State<HistoryChatPage> {

  bool _loading = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // Future.delayed(Duration(seconds: 1), () {
    //   print("开始加载");
    //   widget.valueChanged(false);
    // });
    // Future.delayed(Duration(seconds: 5), (){
    //   print("加载完毕");
    //   widget.valueChanged(true);
    //   setState(() {
    //     _loading = false;
    //   });
    // });
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child: StreamBuilder(
        builder: (BuildContext context,
            AsyncSnapshot<List<HistoryChatModel>> snapshot) {
          return ListView.builder(
            itemBuilder: (context, index) =>
                HistoryChatItem(ObjectKey(snapshot.data[index].friendId),
                    snapshot.data[index], _onTap),
            itemCount: snapshot.data.length,
          );
        },
        stream: widget.bloc.outHistoryChatStream,
        initialData: <HistoryChatModel>[],
      ),
    );
  }

  void _onTap(HistoryChatModel model) {
    if(_loading) return;
    print("onTap model: $model");
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return ChatPage(friendName: model.name, friendId: model.friendId,
        webSocketChannel: widget.webSocketChannel, user: widget.user,);
    }));
  }
}

class HistoryChatItem extends StatelessWidget {
  final HistoryChatModel model;

  final ValueSetter<HistoryChatModel> onTap;

  const HistoryChatItem(Key key, this.model, this.onTap): super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => onTap(model),
      child: Column(
        key: ObjectKey(model.friendId),
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0, bottom: 5.0),
            child: Container(
              height: 100.0,
              alignment: Alignment.centerLeft,
              child: Text(model.toString()),
            ),
          ),
          const Divider(
            height: 1.0,
          )
        ],
      ),
    );
  }
}
